﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplicationBase.Filters
{
    public class IsLoginRedirectAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 在action执行前，判断用户是否登录，拦截未登录用户打开用户个人页面
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            String controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            // 不用登录就可以访问的控制器，登陆后则跳转到用户中心
            List<String> loginNoAccessController = new List<string>();
            loginNoAccessController.Add("Home");
            loginNoAccessController.Add("Login");
            loginNoAccessController.Add("Register");
            HttpCookieCollection cookie = filterContext.HttpContext.Request.Cookies;
            try
            {
                HttpCookie tokenCookie = cookie.Get("authorization_token");
                String token = tokenCookie.Value;
                
                if (loginNoAccessController.Contains(controllerName) && token != null)
                {
                    filterContext.HttpContext.Response.Redirect("/Dashboard/Projects");
                } 
            } catch (Exception e)
            {
                if(!loginNoAccessController.Contains(controllerName))
                {
                    filterContext.HttpContext.Response.Redirect("/");
                }
            }
           
            base.OnActionExecuting(filterContext);
        }
    }
}